import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '@/store'
import getGlobalParams from './getGlobalParams'
import {
  getToken,
  setToken,
  getUserNum,
  getBranchNum
  // getBranchId
} from '@/common/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: getGlobalParams.get('communicationAddress'), // api的base_url
  timeout: 120000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  config.method = 'post';
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  config.data = {
    SYS_HEAD: {
      aumsToken: getToken(),
      TransServiceCode: config.TransServiceCode,
      RequestDate: formatDate(),
      RequestTime: formatTime(),
      ConsumerSeqNo: '02' + formatDate() + FloorRandom(),
      ConsumerIP: '127.0.0.1',
      ConsumerId: '1001',
      ChannelCode: '02',
      AppNum: 'MG',
      userid: getUserNum()
    },
    APP_HEAD: {
      // userId: getUserId(),
      // branchId: getBranchId(),
      BrahNum: getBranchNum(),
      Tlr: getUserNum()
    },
    QUERY_INFO_HEAD: {
      QueryPageNo: config.QueryPageNo,
      QueryRowNum: config.QueryRowNum
    },
    BODY: Object.assign(config.data, configData())
  }
  return config
}, error => {
  Promise.reject(error)
})

function configData() {
  const configData = {
    MainUser: getUserNum(),
    MainBranch: getBranchNum(),
    MainData: formatDate(),
    MainTime: formatTime()
  }
  return configData
}

function formatDate() {
  const date = new Date()
  const y = date.getFullYear() + ''
  let m = date.getMonth() + 1 + ''
  let d = date.getDate() + ''
  m = m.length < 2 ? 0 + m : m;
  d = d.length < 2 ? 0 + d : d;
  return y + m + d
}

function formatTime() {
  const time = new Date()
  var h = String(time.getHours());
  var m = String(time.getMinutes());
  var s = String(time.getSeconds());
  h = h.length < 2 ? '0' + h : h;
  m = m.length < 2 ? '0' + m : m;
  s = s.length < 2 ? '0' + s : s;
  h = h.length < 2 ? 0 + h : h
  s = s.length < 2 ? 0 + s : s
  return h + m + s
}

function FloorRandom() {
  return Math.floor(Math.random() * 10000) + ''
}

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    /**
     * 状态码
     * 000000:成功状态码
     * CIC027:token校验失败
     * CIC028:token已过期
     */
    if (res && res.APP_HEAD.ReturnCode === '000000') {
      if (res && res.APP_HEAD.aumsToken === '' && !store.getters.UserNum) {
        MessageBox.confirm('非法的token，系统将立即退出', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          showCancelButton: false,
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
          return
        })
      }
      if (res && res.APP_HEAD.aumsToken !== undefined) {
        const headData = res.APP_HEAD
        setToken(headData.aumsToken)
      }
      return response.data
    } else if (res && res.APP_HEAD.ReturnCode === 'CIC027' || res.APP_HEAD.ReturnCode === 'CIC028') {
      MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
        return
      })
      // 在出错后不能使用reject 会导致代码后面不执行
    } else if (res && res.APP_HEAD.ReturnCode !== '000000') {
      return response.data;
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // return Promise.reject(error)
  }
)

export default service
